package ljt.music.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;


import java.io.IOException;

import ljt.music.R;
import ljt.music.ui.PlayMusicActivity;
import ljt.music.widget.PlayDialog;

/**
 * @author jiangtao
 */
public class MusicService extends Service implements MediaPlayer.OnBufferingUpdateListener,
    MediaPlayer.OnInfoListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnVideoSizeChangedListener {

  public static String URL = "";

  private MusicReceiver musicReceiver;
  private MediaPlayer mediaPlayer;
  private String intentName;
  private String intentId;
  private String intentSubtitle;
  private String intentUrl;
  private String mp3Url;
  private Bitmap notifyBitmap;

  public MusicService() {
  }

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    if (mediaPlayer == null) {
      mediaPlayer = new MediaPlayer();
      mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
          mediaPlayer.start();
        }
      });
    }
    if (musicReceiver == null) {
      musicReceiver = new MusicReceiver();
      IntentFilter filter = new IntentFilter();
      filter.addAction("PLAYING");
      filter.addAction("CHANGE_DATA_SOURCE");
      filter.addAction("PROGRESS");
      registerReceiver(musicReceiver, filter);
    }
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
      Bundle bundle = intent.getExtras();
      if (bundle != null) {
        mp3Url = bundle.getString("mp3Url");
        intentName = bundle.getString("name");
        intentId = bundle.getString("id");
        intentSubtitle = bundle.getString("subtitle");
        intentUrl = bundle.getString("url");
        if (mp3Url != null) {
          Log.i("TAG", "mp3Url:" + mp3Url.toString());
          try {
            mediaPlayer.setDataSource(mp3Url);
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnInfoListener(this);
            mediaPlayer.setOnSeekCompleteListener(this);
            mediaPlayer.setOnVideoSizeChangedListener(this);
            mediaPlayer.prepare();
            loadBitmap();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
    return super.onStartCommand(intent, flags, startId);
  }

  private void loadBitmap() {
    if (notifyBitmap != null) {
      startForeground(1, getNotification());
    }
    SimpleTarget<Bitmap> simpleTarget = new SimpleTarget<Bitmap>() {
      @Override
      public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
        Log.i("TAG", resource.toString());
        notifyBitmap = resource;
        startForeground(1, getNotification());
      }
    };
    if (intentUrl != null) {
      Glide.with(this)
          .load(intentUrl)
          .asBitmap()
          .into(simpleTarget);
    }
  }

  private Notification getNotification() {
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setShowWhen(false);
    mBuilder.setAutoCancel(false);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher_round);
//    mBuilder.setLargeIcon(((BitmapDrawable)getDrawable(R.mipmap.ic_launcher)).getBitmap());
//    mBuilder.setContentText("thisiscontent");
//    mBuilder.setContentTitle("this is title");
//    return build;

    Notification notification;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
      notification = mBuilder.getNotification();
    } else {
      mBuilder.setStyle(new NotificationCompat.BigTextStyle());
      notification = mBuilder.build();
    }

    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification);
    contentView.setImageViewBitmap(R.id.image, notifyBitmap);
    contentView.setTextViewText(R.id.title, intentName);
    contentView.setTextViewText(R.id.text, intentSubtitle);
    if (mediaPlayer.isPlaying()) {
      contentView.setImageViewResource(R.id.controller, R.drawable.image_btn_pause);
    } else {
      contentView.setImageViewResource(R.id.controller, R.drawable.image_btn_play);
    }
    notification.contentView = contentView;
    notification.bigContentView = contentView;

    Intent notificationIntent = new Intent(this, PlayMusicActivity.class);
    notificationIntent.putExtra("name", intentName);
    notificationIntent.putExtra("id", intentId);
    notificationIntent.putExtra("subtitle", intentSubtitle);
    notificationIntent.putExtra("url", intentUrl);
    Log.i("TAG", intentName);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notification.contentIntent = contentIntent;

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(1, notification);
    return notification;
  }

  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    mediaPlayer.start();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    mediaPlayer.stop();
    unregisterReceiver(musicReceiver);
    stopForeground(true);
  }

  /**
   * 缓存
   *
   * @param mp
   * @param percent
   */
  @Override
  public void onBufferingUpdate(MediaPlayer mp, int percent) {

    Intent mIntent = new Intent(PlayDialog.MUSIC_RECEIVER_ACTION);
    mIntent.putExtra("percent", percent);
    mIntent.putExtra("CurrentPosition", mp.getCurrentPosition());
    mIntent.putExtra("isPlaying", mp.isPlaying());
    mIntent.putExtra("Duration", mp.getDuration());
    sendBroadcast(mIntent);
    loadBitmap();
  }

  @Override
  public boolean onInfo(MediaPlayer mp, int what, int extra) {
    switch (what) {
      case MediaPlayer.MEDIA_INFO_UNKNOWN:
        Log.i("TAG", "onInfo:MEDIA_INFO_UNKNOWN");
        break;
      case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
        Log.i("TAG", "onInfo:MEDIA_INFO_VIDEO_TRACK_LAGGING");
        break;
      case MediaPlayer.MEDIA_INFO_BUFFERING_START:
        Log.i("TAG", "onInfo:MEDIA_INFO_BUFFERING_START");
        break;
      case MediaPlayer.MEDIA_INFO_BUFFERING_END:
        Log.i("TAG", "onInfo:MEDIA_INFO_BUFFERING_END");
        break;
      case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:
        Log.i("TAG", "onInfo:MEDIA_INFO_METADATA_UPDATE");
        break;
      case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
        Log.i("TAG", "onInfo:MEDIA_INFO_BAD_INTERLEAVING");
        break;
      case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
        Log.i("TAG", "onInfo:MEDIA_INFO_NOT_SEEKABLE");
        break;
      default:
    }
    return false;
  }

  @Override
  public void onSeekComplete(MediaPlayer mp) {
    Log.i("TAG", "onSeekComplete:");
  }

  @Override
  public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
    Log.i("TAG", "onVideoSizeChanged->" + "width:" + width);
    Log.i("TAG", "onVideoSizeChanged->" + "height:" + height);
  }

  public class MusicReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if (action == null) {
        return;
      }
      if (action.equals("PLAYING")) {
        if (mediaPlayer.isPlaying()) {
          mediaPlayer.pause();
        } else {
          mediaPlayer.start();
        }
      } else if (action.equals("CHANGE_DATA_SOURCE")) {
        Log.i("TAG", "CHANGE_DATA_SOURCE");
        try {
          Bundle bundle = intent.getExtras();

          if (bundle == null) {
            return;
          }
          mp3Url = bundle.getString("mp3Url");
          intentName = bundle.getString("name");
          intentId = bundle.getString("id");
          intentSubtitle = bundle.getString("subtitle");
          intentUrl = bundle.getString("url");

          mediaPlayer.stop();
          mediaPlayer.reset();
          mediaPlayer.setDataSource(mp3Url);
          mediaPlayer.prepare();
          mediaPlayer.start();

          loadBitmap();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else if (action.equals("PROGRESS")) {
        mediaPlayer.seekTo(intent.getIntExtra("progress", 0));
      }
    }

  }
}
